import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: resolve => require(['@/components/Login'], resolve),
    meta: {
      title: 'Demo-登录'
    }
  },
  {
    path: '/register',
    component: resolve => require(['@/components/Register'], resolve),
    meta: {
      title: 'Demo-注册'
    }
  },
  {
    path: '/index',
    component: resolve => require(['@/components/Index'], resolve),
    redirect: '/home',
    children: [
      { path: '/home', component: resolve => require(['@/components/Home'], resolve), meta: { title: 'Demo-首页' } },
      { path: '/basic/environment', component: resolve => require(['@/components/basic/Environment'], resolve), meta: { title: 'Demo-环境' } },
      { path: '/api/project', component: resolve => require(['@/components/api/Project'], resolve), meta: { title: 'Demo-项目' } },
      { path: '/api/interface', component: resolve => require(['@/components/api/Interface'], resolve), meta: { title: 'Demo-接口' } },
      { path: '/api/function', component: resolve => require(['@/components/api/Function'], resolve), meta: { title: 'Demo-函数' } },
      { path: '/api/config', component: resolve => require(['@/components/api/Config'], resolve), meta: { title: 'Demo-配置' } },
      { path: '/api/case', component: resolve => require(['@/components/api/Testcase'], resolve), meta: { title: 'Demo-用例' } },
      { path: '/api/suite', component: resolve => require(['@/components/api/Suite'], resolve), meta: { title: 'Demo-套件' } },
      { path: '/product/report', component: resolve => require(['@/components/product/Report'], resolve), meta: { title: 'Demo-报告' } },
      { path: '/system/user', component: resolve => require(['@/components/system/User'], resolve), meta: { title: 'Demo-用户' } }
    ]
  }
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function replace (location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  routes
})

export default router

// 页面跳转路由导航守卫
router.beforeEach((to, from, next) => {
  // 去登录或注册页直接放行
  if (to.path === '/login') {
    window.sessionStorage.clear()
    return next()
  }
  if (to.path === '/register') {
    window.sessionStorage.clear()
    return next()
  }
  const tokenStr = window.sessionStorage.getItem('token')
  // token不存在则不跳转
  if (!tokenStr) return next('/')
  // 否则放行
  next()
})
